c# 验证excel文件是否损坏,如果损坏则弹出一个消息框 |
您所在的位置:网站首页 › excel 弹出窗口 › c# 验证excel文件是否损坏,如果损坏则弹出一个消息框 |
问题描述
我是C#的新手,我正在执行一个窗口表单程序,该程序检查是否存在Excel文件.如果存在,则需要验证Excel文件是否损坏,但我不知道如何编写代码.我完成的excel文件的一部分. # int point = 0; if (File.Exists(path1[0])) { MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Tranfser Error"); point = 1; } else { for (int x = 1; x < path1.Length; x++) { if (File.Exists(path1[x])) { MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Error"); point = 1; } } } if (File.Exists(path2[0])) { MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful"); point = 1; } else { for (int x = 1; x < path2.Length; x++) { if (File.Exists(path2[x])) { MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Transfer Successful"); point = 1; } } } if (File.Exists(path3)) { MessageBox.Show("Sales " + Year + "-" + Month + "-" + Day + " Havent Transfer"); point = 1; } if (point == 0) { MessageBox.Show("No File of the date "+ Year +"-"+ Month +"-"+ Day); } 推荐答案看起来您需要检查多个路径的存在和文件格式吗?如果是这样,请更好地构建您的代码.但是,以下功能应为您提供预期的结果.这使用Epplus库,通过Nuget安装. enum ExcelFileTestResult { FileNotFound, ValidFormat, //File found, valid excel InvalidFormat //File found but not valid excel } public static ExcelFileTestResult CheckExcelFile(string path) { ExcelFileTestResult result = ExcelFileTestResult.FileNotFound; if (File.Exists(path)) { FileInfo fi = new FileInfo(path); try { // Trying to read file using EPPlus // if the file is not valid format, it will throw error using (ExcelPackage p = new ExcelPackage(fi)) { result = ExcelFileTestResult.ValidFormat; } } catch (InvalidDataException ex) { result = ExcelFileTestResult.InvalidFormat; } } return result; }注意: epplus仅适用于XLSX,而不是XLS. https://github.com/jankallman/epplus 本文地址:https://www.itbaoku.cn/post/2354438.html?view=all |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |